package com.lcsuo.common.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.lcsuo.bean.authority.Token;
import com.lcsuo.service.authority.TokenService;
import com.lcsuo.utils.Constants;
import com.lcsuo.utils.RestfulResponseBody;
import com.lcsuo.utils.web.RequestUtils;
import com.lcsuo.utils.web.ResponseUtils;

/**
 * 
 * token拦截器
 * @author Sorin
 *
 */
public class TokenInterceptor extends HandlerInterceptorAdapter{

	@Autowired
	private TokenService tokenService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		//获取请求中的token
		String token = request.getHeader("t");
		if (StringUtils.isEmpty(token)) token = request.getParameter("t");
		Token checkToken = tokenService.checkToken(token, request.getHeader("User-Agent"), 
				RequestUtils.getIpAddr(request));
		if(checkToken == null){//校验失败
			RestfulResponseBody body = new RestfulResponseBody();
			body.setReason("验证不通过");
			body.setResultFlag(Constants.resultType.ERROR);
			response.setStatus(401);
			ResponseUtils.renderJson(response, JSON.toJSONString(body));
			return false;
		}
		//校验通过
		request.setAttribute("userId", checkToken.getUserid());
		return true;
	}
}
